package util;

/*
 *
 * Copyright (c) 2009, Sun Microsystems, Inc.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of Sun Microsystems nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.list.DefaultListCellRenderer;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/**
 * Base class for a demo contains common code for all demo pages
 *
 * @author Shai Almog
 */
public abstract class Menu {

    /**
     * returns the name of the demo to display in the list
     */
    public Color color = new Color();
    public ActionListener a;
    public String Clicked = "";
    // Form f;
    Vector lists = new Vector();
    Vector buttons = new Vector();
    public String curr_list;
    public String last_list;
    public List current;
    int layout = 0;
    int transition = 1;
    String backround = "backround.png";
    ActionListener ListActions;
    public Form f = null;
    public boolean build_me_a_reader = false;
    public String reader = "";
    public String Name = "";
    private Timer myRefreshTimer = new Timer();
    private TimerTask updater = null;

    /**
     * Invoked by the main code to start the demo
     */
    public void cleanup() {
        updater = null;
        f = null;
        reader = "";
        buttons.removeAllElements();
        lists.removeAllElements();
        ListActions = null;
        a = null;
        build_me_a_reader = false;
        recycleBin();
        System.gc();
    }

    public final void run(ActionListener commandListener) {
        System.gc();
        //_____________Pre-Initialized code____________________
        f = new Form(getName());
        Listener keyListener = new Listener(f);
        ListActions = ListListener(f);
        f.removeAll();
        a = commandListener;
        f.setCommandListener(commandListener);
        if (this.getName().equalsIgnoreCase("MainMenu")) {

            f.addCommand(new Command("Exit"));
        } else {
            f.addCommand(new Command("Back"));
        }
        //f.addCommand(new Command("MainMenu"));

        //______________Initialize_code_________________________

        execute(f);
        updater = new RefreshTask();
        updater.run();

        myRefreshTimer.schedule(updater, 0, 100);


        //______________post initialized code___________________

        Transition(f);
        Layout(f);

        if (!lists.isEmpty()) {
            current = (List) lists.elementAt(0);
            f.addComponent(current);
        }
        if (!buttons.isEmpty()) {
            for (int i = 0; i < buttons.size(); i++) {
                f.addComponent((Button) buttons.elementAt(i));

            }
        }
        addKeyListeners(keyListener, f);
        ListListener(f);
        setBackroundImage(f);
        f.show();



    }

    private void addKeyListeners(Listener l, Form f) {
        f.addKeyListener(-6, l);
        f.addKeyListener(-10, l);
        f.addKeyListener(0, l);
        f.addKeyListener(-7, l);
        f.addKeyListener(-8, l);
        f.addKeyListener(-1, l);
        f.addKeyListener(-2, l);
        f.addKeyListener(-3, l);
        f.addKeyListener(-4, l);
        f.addKeyListener(-5, l);
        f.addKeyListener(49, l);
        f.addKeyListener(50, l);
        f.addKeyListener(51, l);
        f.addKeyListener(52, l);
        f.addKeyListener(53, l);
        f.addKeyListener(54, l);
        f.addKeyListener(55, l);
        f.addKeyListener(56, l);
        f.addKeyListener(57, l);
        f.addKeyListener(42, l);
        f.addKeyListener(48, l);
        f.addKeyListener(35, l);
    }

    public abstract void update();

    protected abstract void recycleBin();

    private ActionListener ListListener(final Form f) {
        ActionListener c = new ActionListener() {

            public void actionPerformed(ActionEvent ae) {

                if (!setList(current.getSelectedItem().toString(), f)) {
                    System.out.println(current.getSelectedItem().toString());
                    build_me_a_reader = true;
                    reader = current.getSelectedItem().toString();
                }
            }
        };
        return c;
    }

    public void addList(String s[], String Name) {
        List l = new List(s);
        l.addActionListener(ListActions);
        l.addActionListener(a);
        l.setFocusPainted(false);
        l.setListCellRenderer(autoScroller());
        l.setUIID(Name);
        if (!lists.contains(l)) {
            lists.addElement(l);
        }
    }

    public void addList(Vector strings, String Name) {
        List l = new List(strings);
        l.addActionListener(ListActions);
        l.addActionListener(a);
        l.setFocusPainted(false);
        l.setListCellRenderer(autoScroller());
        l.setUIID(Name);
        if (!lists.contains(l)) {
            lists.addElement(l);
        }
    }

    public List getList(String list) {
        for (int i = 0; i < lists.size(); i++) {
            List l = (List) lists.elementAt(i);
            if (l.getUIID().equalsIgnoreCase(list)) {
                return l;
            }
        }
        return null;
    }

    public boolean setList(String list, Form f) {
        List l = getList(list);

        if (l != null) {
            f.replace(current, getList(list), null);
            current = l;
            return true;
        }
        return false;
    }

    public void transSetList(Form f, String Name) {
        if (current.equals("start")) {
            f.replace(getList(curr_list), getList("English"), null);
            last_list = Name;
            curr_list = "English";
        } else if (curr_list.equals("English")) {
            int search = 0;
            String word = "";
            f.removeAll();
            f.repaint();
            search = getList(curr_list).getSelectedIndex();
            getList(last_list).setSelectedIndex(search);
            word = getList(last_list).getSelectedItem().toString();
            TextArea area = new TextArea(word);
            f.addComponent(area);


        } else {
            f.replace(getList(curr_list), getList(Name), null);
            f.repaint();
            curr_list = Name;
        }
    }
//    public void listClickedAction(Form f) {
//        if(this.getName().equalsIgnoreCase("Translator")){
//                transSetList(f, current.getSelectedItem().toString());
//        }else{
//             setList(current.getSelectedItem().toString(), f);
//        }
//
//    }
//>>>>>>> .r49

    public void setBackround(String Image_name) {
        backround = Image_name;
    }

    private void setBackroundImage(Form f) {
        try {
            f.setBgImage(Image.createImage("/images/" + backround));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void Key_UP(Form f) {
    }

    ;

    public void Key_DOWN(Form f) {
    }

    ;

    public void Key_LEFT(Form f) {
    }

    ;

    public void Key_RIGHT(Form f) {
    }

    ;

    public void Key_CENTRE(Form f) {
    }

    ;

    public void Key_LEFTBUTTON(Form f) {
    }

    ;

    public void Key_RIGHTBUTTON(Form f) {
    }

    ;

    public void Key_0(Form f) {
    }

    ;

    public void Key_1(Form f) {
    }

    ;

    public void Key_2(Form f) {
    }

    ;

    public void Key_3(Form f) {
    }

    ;

    public void Key_4(Form f) {
    }

    ;

    public void Key_5(Form f) {
    }

    ;

    public void Key_6(Form f) {
    }

    ;

    public void Key_7(Form f) {
    }

    ;

    public void Key_8(Form f) {
    }

    ;

    public void Key_9(Form f) {
    }

    ;

    public void Key_STAR(Form f) {
    }

    ;

    public void Key_HASH(Form f) {
    }

    ;

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l = new Label(label);
        Dimension d = l.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        l.setPreferredSize(d);
        pair.addComponent(BorderLayout.WEST, l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    /**
     * Helper method that allows us to create a pair of components label and the given
     * component in a horizontal layout
     */
    protected Container createPair(String label, Component c) {
        return createPair(label, c, 0);
    }

    public Button addButton(String name, String next, String picture, int textColor) {

        final Button c = new Button();
        try {
            final Button b = new Button(Image.createImage("/images/" + picture + "_unsel.png"));
            b.setUIID(name);
            b.setText(name);
            b.setRolloverIcon(Image.createImage("/images/" + picture + "_sel.png"));
            b.setAlignment(Label.CENTER);
            b.setUIID(next);
            b.setTextPosition(Label.BOTTOM);
            b.setFocusable(true);
            b.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    Clicked = b.getUIID();
                }
            });
            b.addActionListener(a);
            b.setFocusPainted(false);
            b.getStyle().setFgColor(textColor);
            if (!buttons.contains(b)) {
                buttons.addElement(b);
            }
            return b;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return c;
    }

    private void Layout(Form f) {
        int i = layout;
        if (i == 0) {
            f.setLayout(new GridLayout(10, 2));
        }
        if (i == 1) {
            f.setLayout(new GridLayout(10, 1));
        }
        if (i == 2) {
            f.setLayout(new GridLayout(1, 10));
        }
        if (i == 3) {
            f.setLayout(new GridLayout(10, 3));
        }
        if (i == 4) {
            f.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        }

    }

    private void Transition(Form f) {
        int i = transition;
        if (i == 0) {
            f.setTransitionOutAnimator(null);
        }
        if (i == 1) {
            f.setTransitionOutAnimator(
                    CommonTransitions.createSlide(
                    CommonTransitions.SLIDE_HORIZONTAL, true, 200));
        }
        if (i == 2) {
            f.setTransitionOutAnimator(
                    CommonTransitions.createSlide(
                    CommonTransitions.SLIDE_HORIZONTAL, false, 200));
        }
        if (i == 3) {
        }
        if (i == 4) {
        }
    }

    public void setLayout(int i) {
        layout = i;

    }

    public void setTransition(int i) {
        transition = i;
    }

    protected abstract void execute(Form f);

    public String getName() {
        //designed by niall to deperate the class name from its package
        String Name = this.getClass().getName();
        for (int i = Name.length() - 1; i > 0; i--) {
            if (Name.charAt(i) == '.') {
                String s = Name.substring(i + 1, Name.length());
                Name = s;
                break;
            }
        }
        return Name;

    }

    public TickerRenderer autoScroller() {
        return new TickerRenderer();
    }

    public class Listener implements ActionListener {

        Form f;

        public Listener(Form F) {
            f = F;
        }

        public void actionPerformed(ActionEvent ae) {
            int key = ae.getKeyEvent();
            switch (key) {
                case -1:
                    Key_UP(f);
                    f.repaint();
                    break;
                case -2:
                    Key_DOWN(f);
                    f.repaint();
                    break;
                case -3:
                    Key_LEFT(f);
                    f.repaint();
                    break;
                case -4:
                    Key_RIGHT(f);
                    f.repaint();
                    break;
                case -5:
                    Key_CENTRE(f);
                    f.repaint();
                    break;
                case -6:
                    Key_LEFTBUTTON(f);
                    f.repaint();
                    break;
                case -7:
                    Key_RIGHTBUTTON(f);
                    f.repaint();
                    break;
                case 49:
                    Key_1(f);
                    f.repaint();
                    break;
                case 50:
                    Key_2(f);
                    f.repaint();
                    break;
                case 51:
                    Key_3(f);
                    f.repaint();
                    break;
                case 52:
                    Key_4(f);
                    f.repaint();
                    break;
                case 53:
                    Key_5(f);
                    f.repaint();
                    break;
                case 54:
                    Key_6(f);
                    f.repaint();
                    break;
                case 55:
                    Key_7(f);
                    f.repaint();
                    break;
                case 56:
                    Key_8(f);
                    f.repaint();
                    break;
                case 57:
                    Key_9(f);
                    f.repaint();
                    break;
                case 42:
                    Key_STAR(f);
                    f.repaint();
                    break;
                case 48:
                    Key_0(f);
                    f.repaint();
                    break;
                case 35:
                    Key_HASH(f);
                    f.repaint();
                    break;

            }
            //  throw new UnsupportedOperationException("Not supported yet.");
        }
    }

    private class RefreshTask extends TimerTask {

        public void run() {

            update();

        }
    }

    public class TickerRenderer extends DefaultListCellRenderer {

        private DefaultListCellRenderer selectedRenderer = new DefaultListCellRenderer(false);
        private List parentList;

        public TickerRenderer() {
            super(false);
        }

        public boolean animate() {
            if (parentList != null && parentList.getComponentForm() != null) {
                if (selectedRenderer.isTickerRunning()) {
                    if (selectedRenderer.animate()) {
                        parentList.repaint();
                    }
                }
            }
            return super.animate();
        }

        public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {
            if (isSelected) {
                selectedRenderer.getListCellRendererComponent(list, value, index, isSelected);

// sometimes the list asks for a dummy selected value for size calculations and this might
// break the tickering state
                if (index == list.getSelectedIndex()) {
                    if (selectedRenderer.shouldTickerStart()) {
                        if (!selectedRenderer.isTickerRunning()) {
                            parentList = list;
                            list.getComponentForm().registerAnimated(this);
                            selectedRenderer.startTicker(UIManager.getInstance().getLookAndFeel().getTickerSpeed(), true);
                        }
                    } else {
                        if (selectedRenderer.isTickerRunning()) {
                            selectedRenderer.stopTicker();
                        }
                    }
                }
                return selectedRenderer;
            } else {
                return super.getListCellRendererComponent(list, value, index, isSelected);
            }
        }
    }
}

